<template>
  <div class="context">
    <van-nav-bar
      :title="userInfo.regStatus == 4 ? '资料修改' : '商户入网'"
      left-arrow
      @click-left="back"
    />
    <Remarks v-if="userInfo.regStatus == 4" :contents="userInfo.remarks" />

    <van-form @submit="onSubmit">
      <van-field
        is-link
        readonly
        v-model="formData.openTypeText"
        label="开通类型"
        placeholder="请选择"
        :rules="[{ required: true, message: '请选择开通类型' }]"
        @click="userInfo.regStatus == 4 ? () => {} : showPopup(1)"
        :disabled="userInfo.regStatus == 4"
      />
      <!-- <van-field
        v-if="formData.openType != 3"
        is-link
        readonly
        class="mt-margin"
        v-model="formData.merchantText"
        label="所属商户"
        placeholder="请选择商户，输入关键字筛选"
        @click="selectMerchant"
      /> -->
      <p class="notes" v-if="[1, 2].includes(Number(formData.openType))">
        独立经营门店：支持分店有独立的结算账户
      </p>
      <p class="notes" v-if="[1, 2].includes(Number(formData.openType))">
        直营连锁门店：与主店同一结算账户
      </p>
      <van-field
        v-if="formData.openType != 1"
        is-link
        readonly
        class="mt-margin"
        v-model="formData.merchantTypeText"
        label="商户类型"
        placeholder="请选择"
        :rules="[{ required: true, message: '请选择商户类型' }]"
        @click="userInfo.regStatus == 4 ? () => {} : showPopup(2)"
        :disabled="userInfo.regStatus == 4"
      />
      <van-field
        v-if="formData.openType != 1"
        is-link
        readonly
        class="mt-margin"
        v-model="formData.firstSettleTypeText"
        label="结算周期"
        placeholder="请选择结算周期"
        :rules="[{ required: true, message: '请选择结算周期' }]"
        @click="showPopup(3)"
      />
      <p class="notes" v-if="showfirstSettleTypeMsg">
        当前所选商户类型无结算周期，请联系代理。
      </p>
      <van-field
        v-if="formData.openType != 1"
        is-link
        readonly
        v-model="formData.accountTypeText"
        label="账户类型"
        placeholder="请选择"
        :rules="[{ required: true, message: '请选择账户类型' }]"
        @click="showPopup(4)"
      />
      <van-field
        v-if="formData.openType != 1"
        is-link
        readonly
        class="mt-margin"
        v-model="formData.payTypeText"
        label="支付方式"
        placeholder="请选择"
        :rules="[{ required: true, message: '请选择支付方式' }]"
        @click="showPopup(5)"
      />
      <van-field
        v-if="firstSettleTimeVis"
        is-link
        readonly
        class="mt-margin"
        v-model="formData.firstSettleTimeText"
        label="定时结算时间"
        placeholder="请选择"
        :rules="[{ required: true, message: '请选择定时结算时间' }]"
        @click="showPopup(6)"
      />
      <!-- <p
        class="notes"
        v-show="formData.payType == 2 && agentInfo.cardEntryExplain"
      >
        {{ agentInfo.cardEntryExplain }}
      </p> -->
      <div v-if="formData.payType == 2 && eleCardDesc" class="notes">
        {{ eleCardDesc || "" }}
      </div>
      <div style="margin: 16px">
        <van-button
          block
          type="info"
          color="#FFB72F"
          class="next-step-btn"
          native-type="submit"
          >下一步</van-button
        >
      </div>
    </van-form>
    <!-- 以下是弹窗内容 -->
    <van-popup v-model="show[1]" position="bottom">
      <van-picker
        title="开通类型"
        show-toolbar
        :columns="getOpenTypes"
        @confirm="selectOpenType"
        @cancel="onCancel(1)"
      />
    </van-popup>
    <van-popup v-model="show[2]" position="bottom">
      <van-picker
        title="商户类型"
        show-toolbar
        :columns="merchantTypeList"
        @confirm="selectMerchantType"
        @cancel="onCancel(2)"
      />
    </van-popup>
    <van-popup v-model="show[3]" position="bottom">
      <van-picker
        title="结算周期"
        show-toolbar
        :columns="firstSettleTypeList"
        @confirm="firstSettleTypes"
        @cancel="onCancel(3)"
      />
    </van-popup>
    <van-popup v-model="show[4]" position="bottom">
      <van-picker
        title="账户类型"
        show-toolbar
        :columns="accountTypeList"
        @confirm="selectAccountTyepe"
        @cancel="onCancel(4)"
      />
    </van-popup>
    <van-popup v-model="show[5]" position="bottom">
      <van-picker
        title="支付方式"
        show-toolbar
        :columns="payTypeList"
        @confirm="selectPayType"
        @cancel="onCancel(5)"
      />
    </van-popup>
    <van-popup v-model="show[6]" position="bottom">
      <van-picker
        title="定时结算时间"
        show-toolbar
        :columns="firstSettleTimeList"
        @confirm="selectFirstSettleTime"
        @cancel="onCancel(6)"
      />
    </van-popup>
  </div>
</template>

<script>
import { Toast } from "vant";

import { save, queryRegisterConfig } from "@/api/stores";
import {
  getCommonConfigByTenantId,
  getMerchantDetail,
  storeCount,
  getEntryAllowedInfo,
} from "@/api/merchant";
import { getChannelDetail } from "@/api/channel";

import { merchantAccountTypeHandler } from "./config";
export default {
  name: "TypeSelect",
  components: {
    Remarks: () => import("@/components/Remarks"),
  },
  data() {
    return {
      formData: {
        firstSettleType: "",
        merchantType: "",
        openType: "",
        payType: "",
        accountType: "",
        firstSettleTime: "",
      },
      firstSettleTypeListData: [],

      openTypies: [],
      show: {
        1: false,
        2: false,
        3: false,
        4: false,
        5: false,
        6: false,
      },
      merchantInfo: {},
      isAlone: false,
      isStrage: false,
      showfirstSettleTypeMsg: false,
      eleCardDesc: "",
      configData: {
        1: {},
        2: {},
        3: {},
      },
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo;
    },
    merchantForm() {
      return this.$store.state.merchant;
    },

    agentInfo() {
      return this.$store.state.user.agentInfo;
    },
    channelInfo() {
      return this.$store.state.user.channelInfo;
    },
    Autonomy() {
      return this.$store.state.common.Autonomy;
    },
    settlement() {
      return this.$store.state.settlement;
    },
    getOpenTypes() {
      const openTypeList = [
        // {
        //   text: "商户",
        //   value: "3",
        // },
        {
          text: "独立经营门店",
          value: "2",
        },
        {
          text: "直营连锁门店",
          value: "1",
        },
      ];
      let list = [];
      if (this.userInfo.regApproach == "touristAdd") {
        list = openTypeList.filter((item) => item.value !== "1");
      } else {
        list = openTypeList.filter((item) => item.value !== "3");
      }

      return list;
    },
    merchantTypeList() {
      let list = [
        {
          text: "企业",
          value: "1",
        },
        {
          text: "个体",
          value: "2",
        },
        {
          text: "小微",
          value: "3",
        },
      ];
      return this.formData.openType ? list : [];
    },
    firstSettleTimeList() {
      let arr = [];
      // 只有需要展示时间的时候 才计算
      if (this.firstSettleTimeVis) {
        const { payType } = this.formData;
        const { platSettleTime } =
          this.getPayTypeConfig[payType] &&
          this.getPayTypeConfig[payType].length
            ? this.getPayTypeConfig[payType][0]
            : {};
        if (platSettleTime) {
          arr = platSettleTime.split(",").map((item) => {
            return {
              text: `${item}:00`,
              value: item,
            };
          });
        }
      }
      return arr;
    },
    firstSettleTypeList() {
      const res = this.getFirstSettleConfig;
      const list = Object.keys(res);
      console.log(res, "list");
      return list;
    },
    accountTypeList() {
      const res = this.getAccountTypeConfig;
      const list = Object.keys(res);
      const selection = [
        {
          value: "1",
          text: "法人对公",
        },
        {
          value: "2",
          text: "法人对私",
        },
        {
          value: "3",
          text: "非法人对私",
        },
      ].filter((item) => list.includes(item.value));
      console.log(selection, list, "list");
      return selection;
    },
    payTypeList() {
      const list = Object.keys(this.getPayTypeConfig);
      const selection = [
        {
          text: "扫码",
          value: "1",
        },
        {
          text: "扫码+刷卡",
          value: "2",
        },
      ].filter((item) => list.includes(item.value));
      return selection;
    },
    getFirstSettleConfig() {
      const { merchantType } = this.formData;
      const firstSettle = this.configData[merchantType] || {};
      if (!this.configData[merchantType]) {
        this.formData.merchantType = "";
      }
      return merchantType ? firstSettle : {};
    },
    getAccountTypeConfig() {
      const { firstSettleTypeText } = this.formData;
      const accountType = this.getFirstSettleConfig[firstSettleTypeText] || {};
      // 检测是否有对应的周期
      if (!Object.keys(accountType).length) {
        this.formData.firstSettleTypeText = "";
        this.formData.firstSettleType = "";
      }
      return firstSettleTypeText ? accountType : {};
    },
    getPayTypeConfig() {
      const { accountType } = this.formData;
      const payType = this.getAccountTypeConfig[accountType] || {};
      if (!Object.keys(payType).length) {
        this.formData.accountType = "";
      }
      return accountType ? payType : {};
    },
    getChannelConfig() {
      const { payType } = this.formData;
      const channel =
        this.getPayTypeConfig[payType] && this.getPayTypeConfig[payType].length
          ? this.getPayTypeConfig[payType][0]
          : {};
      if (!Object.keys(channel).length) {
        this.formData.payType = "";
      }
      return payType ? channel : {};
    },
    firstSettleTimeVis() {
      const { firstSettleTypeText = "", openType } = this.formData;
      // console.log("this.formdata", this.formData);
      // 结算周期 为【定时结算】才展示 定时结算时间
      return openType != 1 && firstSettleTypeText.indexOf("定时结算") > -1;
    },
  },

  methods: {
    init() {
      this.$nextTick(() => {
        let form = this.$store.state.merchant;
        let newForm = JSON.parse(JSON.stringify(form));
        const { firstSettleTypeText, firstSettleType } = form;
        this.formData = {
          ...newForm,
          firstSettleType: firstSettleType,
          firstSettleTypeText: firstSettleTypeText,
          accountType: this.settlement.acconutType,
          accountTypeText: this.settlement.accountTypeText,
        };
        this.getDesc();
        if (this.userInfo.merchantId) {
          getMerchantDetail(this.userInfo.merchantId).then((res) => {
            if (res.data.defaultChannelCode) {
              this.$store.commit(
                "setDefaultChannelCode",
                res.data.defaultChannelCode
              );
            }
            this.defaultChannelCode = res.data.defaultChannelCode;
            this.merchantInfo = res.data;
            Toast.clear();

            // if (res.data.merchantType == 3) {
            //   storeCount(this.userInfo.merchantId).then((s) => {
            //     getCommonConfigByTenantId().then((v) => {
            //       const fenleiTotal = s.data.fenleiTotal;
            //       const {
            //         microOpenDirectlyStoreFlag,
            //         microOpenDirectlyStoreNum,
            //       } = v.data;
            //       // 独立
            //       this.isAlone =
            //         microOpenDirectlyStoreFlag == 1 &&
            //         microOpenDirectlyStoreNum <= fenleiTotal[1];
            //       //   判断是否限制直营
            //       this.isStrage =
            //         microOpenDirectlyStoreFlag == 1 &&
            //         microOpenDirectlyStoreNum <= fenleiTotal[2];
            //     });
            //   });
            // }
          });
        } else {
          Toast.clear();
        }
      });
    },
    onSubmit() {
      let firstSettleType = {};
      if (this.formData.openType == 1) {
        const {
          merchantType,
          merchantAccountType,
          defaultChannelCode,
          defaultChannelId,
          defaultSettle,
          entryChannelId,
          entryChannelCode,
        } = this.merchantInfo;
        this.formData.merchantType = merchantType;
        this.formData.accountType = merchantAccountType;
        // 获取新结算周期value
        const settleTypeList = [
          defaultChannelId || entryChannelId,
          defaultSettle,
          defaultChannelCode || entryChannelCode,
        ].filter((item) => item);

        firstSettleType = {
          channelCode: settleTypeList[2],
          channelId: settleTypeList[0],
          value: settleTypeList[1],
          settleType: defaultSettle,
        };
      } else {
        firstSettleType = {
          ...this.getChannelConfig,
          text: this.formData.firstSettleTypeText,
          value: this.getChannelConfig.platSettleType,
        };
      }
      // console.log(
      //   this.formData,
      //   this.formData.merchantType,
      //   merchantAccountTypeHandler[this.formData.merchantType],
      //   this.formData.accountType,
      //   firstSettleType,
      //   "this.formData.accountType"
      // );
      const merchantAccountType = merchantAccountTypeHandler[
        this.formData.merchantType
      ].find((item) => item.value === Number(this.formData.accountType));

      this.$store.commit("firstSettleType", firstSettleType);
      this.$store.commit("setChannelCode", firstSettleType.channelCode);
      this.$store.dispatch("getChannelInfo", firstSettleType.channelCode);
      const query = {
        channelId: firstSettleType.channelId || this.channelInfo.id,
        merchantNature: this.formData.openType,
        queryUsage: 1,
        merchantType: Number(this.formData.merchantType),
        merchantAccountType: merchantAccountType.match,
      };
      console.log(query);
      //  添加检查限制提示
      this.checkStoreLimit().then(() => {
        this.$store
          .dispatch("getConfig", query)
          .then(() => {
            this.$router.push("/submitInfo/step2");
          })
          .catch(console.log);
      });
    },
    back() {
      document.title = "返回APP";
    },

    selectOpenType(data, index) {
      this.formData.openTypeText = data.text;
      this.formData.openType = data.value;
      this.$store.commit("setOpenType", data);

      if (data.value == 3 || data.value == 1) {
        this.$store.commit("setMerchant", {
          merchantFullName: "",
          id: "",
        });
        this.formData.merchantText = "";
      }
      if (data.value == 3) {
      } else {
        this.clearData(0);
      }
      this.show[1] = false;
    },
    selectMerchant() {
      if (this.formData.openType == 1 && this.limit) {
        this.$router.push({
          path: "/selectmerchant",
          query: { exceptStoreType: 3 },
        });
      } else {
        this.$router.push({
          path: "/selectmerchant",
        });
      }
    },
    selectMerchantType(data, index) {
      this.formData.merchantTypeText = data.text;
      this.formData.merchantType = data.value;
      this.$store.commit("setMerchantType", data);
      this.show[2] = false;
      this.clearData(1);
    },
    selectPayType(data, index) {
      this.formData.payTypeText = data.text;
      this.formData.payType = data.value;
      this.$store.commit("setPayType", data);
      if (data.value == 1) {
        this.$store.commit("setEquipmentSN", "");
      }
      this.getDesc();
      this.show[5] = false;
    },
    selectFirstSettleTime(data, index) {
      this.formData.firstSettleTimeText = data.text;
      this.formData.firstSettleTime = data.value;
      this.$store.commit("setFirstSettleTime", data);
      this.show[6] = false;
    },
    firstSettleTypes(data) {
      console.log(data);
      this.formData.firstSettleTypeText = data;
      // this.formData.firstSettleType = data;
      this.clearData(2);
      console.log(data);
      this.show[3] = false;
    },

    selectAccountTyepe(data, index) {
      this.formData.accountTypeText = data.text;
      this.formData.accountType = data.value;
      this.$store.commit("setAccountType", data);
      if (data.value == 1) {
        this.$store.commit(
          "ISetAccountName1",
          this.merchantForm.merchantFullName
        );
      }
      if (data.value == 2) {
        this.$store.commit(
          "ISetAccountName1",
          this.merchantForm.merchantFullName
        );
        this.$store.commit("ISetAccountName2", this.merchantForm.legalName);
      }
      this.clearData(3);
      this.show[4] = false;
    },
    showPopup(e) {
      const listHandler = {
        1: { list: "getOpenTypes", errText: "" },
        2: { list: "merchantTypeList", errText: "请更换开通类型" },
        3: { list: "firstSettleTypeList", errText: "请更换商户类型" },
        4: { list: "accountTypeList", errText: "请更换结算周期" },
        5: { list: "payTypeList", errText: "请更换账户类型" },
        6: { list: "firstSettleTimeList", errText: "请更换支付方式" },
      };
      const handler = listHandler[e];
      console.log(this[handler.list], handler.list);
      if (this[handler.list].length) {
        this.show[e] = true;
      } else {
        this.$toast({
          message: handler.errText,
          duration: 2000,
          forbidClick: true,
        });
      }
    },
    onCancel(e) {
      this.show[e] = false;
    },
    getEntryAllowedInfoFun(id) {
      getEntryAllowedInfo(id).then((res) => {
        this.init();
        if (res.code == 200) {
          this.configData = res.data;
        }
      });
    },
    clearData(level) {
      const list = [
        "merchantType",
        "firstSettleType",
        "accountType",
        "payType",
        "firstSettleTime",
      ].filter((_, index) => index >= level);
      list.forEach((item) => {
        this.formData[item] = "";
        this.formData[item + "Text"] = "";
      });
    },

    getDesc() {
      if (
        this.formData.openType &&
        this.formData.openType != 1 &&
        this.formData.payType == 2 &&
        Object.keys(this.getChannelConfig).length
      ) {
        let firstSettleType = this.getChannelConfig;
        const merchantAccountType = merchantAccountTypeHandler[
          this.formData.merchantType
        ].find((item) => item.value === Number(this.formData.accountType));

        const query = {
          channelId: firstSettleType.channelId || this.channelInfo.id,
          merchantNature: this.formData.openType,
          queryUsage: 1,
          merchantType: Number(this.formData.merchantType),
          merchantAccountType: merchantAccountType.match,
        };
        queryRegisterConfig(query).then(({ data, code }) => {
          if (code === 200) {
            const eleCardDesc = data.list.find(
              (item) => item.configEle === "eleCardDesc"
            );
            console.log(eleCardDesc, "eleCardDesc");
            this.eleCardDesc = eleCardDesc ? eleCardDesc.eleDefaultValue : "";
          }
        });
      }
    },
    checkStoreLimit() {
      return new Promise((resolve, reject) => {
        storeCount(this.userInfo.merchantId).then((res) => {
          const fenleiTotal = res.data.fenleiTotal;
          const strageStoreCount = fenleiTotal[1];
          const aloneStoreCount = fenleiTotal[2];
          getCommonConfigByTenantId().then((v) => {
            const {
              // 执照(企业/个体)商户开通直营门店
              creditOpenDirectlyStoreFlag,
              creditOpenDirectlyStoreNum,
              // 商户开通独立经营门店
              merchantOpenStandStoreFlag,
              merchantOpenStandStoreNum,
              // 小微商户开通直营门店
              microOpenDirectlyStoreFlag,
              microOpenDirectlyStoreNum,
            } = v.data;

            const checkCredit =
              this.formData.openType == 1 &&
              [1, 2].includes(this.merchantInfo.merchantType) &&
              creditOpenDirectlyStoreFlag == 1 &&
              creditOpenDirectlyStoreNum <= strageStoreCount
                ? "执照商户开通直营门店已达上限"
                : "";

            const checkMerchant =
              this.formData.openType == 2 &&
              merchantOpenStandStoreFlag == 1 &&
              merchantOpenStandStoreNum <= aloneStoreCount
                ? "独立经营门店开通数量已达上限"
                : "";

            const checkMicro =
              this.formData.openType == 1 &&
              [3].includes(this.merchantInfo.merchantType) &&
              microOpenDirectlyStoreFlag == 1 &&
              microOpenDirectlyStoreNum <= strageStoreCount
                ? "小微商户开通直营门店已达上限"
                : "";
            console.log(this.merchantInfo.merchantType, this.formData.openType);
            console.log(checkCredit, checkMerchant, checkMicro);
            if (checkCredit || checkMerchant || checkMicro) {
              this.$toast({
                message: checkCredit || checkMerchant || checkMicro,
                duration: 2000,
                forbidClick: true,
              });
              reject();
            } else {
              resolve();
            }
          });
        });
      });
    },
  },
  created() {
    const { query = {} } = this.$route;
    Toast.loading({
      message: "加载中...",
      forbidClick: true,
      overlay: true,
    });
    if (Object.keys(query).length) {
      if (query.storeId) {
        this.$store
          .dispatch("setNewStoreInfo", {
            id: query.storeId,
            tenantId: query.tenantId || "000001",
          })
          .then((res) => {
            this.getEntryAllowedInfoFun(res.agentId);
          });
      }
      if (query.token) {
        localStorage.setItem("fuhuibatoken", query.token);
      }
      this.$router.replace({
        path: "/submitInfo/step1",
      });
      this.$store.dispatch("setAutonomy", query.Autonomy || "");
    } else {
      this.getEntryAllowedInfoFun(this.agentInfo.id);
    }
    // getCommonConfigByTenantId().then((v) => {
    //   const { microOpenDirectlyStoreFlag, microOpenDirectlyStoreNum } = v.data;
    //   this.limit =
    //     microOpenDirectlyStoreFlag == 1 && microOpenDirectlyStoreNum == 0;
    // });
  },
  // beforeRouteLeave(to, from, next) {
  //   if (to.path == "/registers") {
  //     this.$dialog
  //       .confirm({
  //         title: "退出商户认证",
  //         message: `<div style="font-size:16px;line-height:12px;">
  //         <p>资料尚未完成，确认是否保存资料？</p>
  //         <p>已保存的资料可在认证页面继续填写</p>
  //         </div>`,
  //         cancelButtonText: "不保存",
  //         cancelButtonColor: "#FFB72F",
  //         confirmButtonText: "保存资料",
  //         confirmButtonColor: "#FFB72F",
  //       })
  //       .then(() => {
  //         // 保存资料
  //         this.$toast({
  //           type: "loading",
  //           message: "正在提交...",
  //           forbidClick: true,
  //           duration: 0,
  //         });
  //         this.$store.commit("setComplete", 0);
  //         save(this.$store.state)
  //           .then((res) => {
  //             document.title = "返回APP";
  //             this.$toast.clear();
  //           })
  //           .catch((err) => {
  //             this.$toast.clear();
  //             document.title = "返回APP";
  //           });
  //       })
  //       .catch(() => {
  //         // 取消
  //         document.title = "返回APP";
  //       });
  //     //   }
  //   } else {
  //     next();
  //   }
  // },
};
</script>
<style scoped lang="less">
/deep/.van-picker-column__item--selected {
  color: #ff9600 !important;
}
/deep/.van-picker__confirm {
  color: #ff9600 !important;
}
/deep/.van-nav-bar__title {
  font-size: 36px !important;
}
/deep/ .van-nav-bar__text {
  color: #ffb72f !important;
}
/deep/ .van-nav-bar__content {
  height: 110px !important;
}
.context {
  background-color: #f5f5f5;
  height: 100vh;
}
.notes {
  font-size: 28px;
  font-weight: 400;
  color: #131313;
  opacity: 0.7;
  padding: 12px 35px;
  line-height: 35px;
  white-space: pre-wrap;
}
</style>
